//
//  LoginViewModel.m
//  DataStatistics
//
//  Created by Kang on 16/6/13.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "LoginViewModel.h"
#import "LoginModel.h"
#import "SearchViewModel.h"
#import "TabBarC.h"
//#import "DeploySDK.h"
#import "GetiPhoneDevice.h"
#import "JPUSH.h"

#define  JSESSIONID @"JSESSIONID"


@interface LoginViewModel ()
@property (assign, nonatomic) BOOL isState; //获取状态
@end

@implementation LoginViewModel

// API职责 --负责发起请求， 不负责返回数据
#pragma mark - 登陆
+ (void) requestWithUrlForLoginIn:(id)obj  andParam:(NSDictionary *)param success:(void(^)(LoginModel * model))success failure:(void(^)(NSString * error))failure {
  
    MDC_INTER_DIC(@"login/wholeloginSubmit.asp", @"NetMethodPOST", @"true");
 __weak typeof(self) weakSelf = self;
    [[UtilToolsClss getUtilTools] addDoLoading];
    [NetRequestClss requestWithUrl:[inter objectForKey:@"mdc_Url"] requestWithParameters:param method:(NetMethod)[inter objectForKey:@"isMethod"] returnSuccess:^(id objs, int status, NSString *mag) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        
        NSLog(@"%@",objs);
        NSString *errorStr = @"";
        int loginResultCode =  [objs[@"body"][@"loginResult"] intValue];
        
        if (loginResultCode == 8) {
            LoginModel *list = [LoginModel mj_objectWithKeyValues:objs[@"body"]];
            //[weakSelf obtainHeadImage:list.headImage];
            [weakSelf obtainHTTPCookie];
            [NSUD setObject:objs[@"body"][@"roleCode"] forKey:@"roleCode"];
            [NSUD setObject:objs[@"body"][@"userName"] forKey:@"userName"];
            
            if (objs) {
                success(list);
                return;
            }
            
        }else {
            NSString *erStr = [NSString stringWithFormat:@"LvcTip_%d",loginResultCode];
            errorStr = NSLocalizedString(erStr, @"请输入账号密码");
        }
        failure(errorStr);
        
    } returnError:^(NSString *err) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        NSLog(@"%@",err);
        failure(err);
    }];
}


#pragma mark - 验证手机注册情况 -已注册或者，未注册
+ (void)requestWithUrlForRegisteredAccountSign:(NSString *)sign andParam:(NSDictionary *)param success:(void (^)(id model))success failure:(void (^)(NSString *err))failure {
    [[UtilToolsClss getUtilTools] addDoLoading];
    [NetRequestClss requestWithUrl:@"userInfo/phoneVerify.asp" requestWithParameters:param method:NetMethodPOST returnSuccess:^(id objs, int status, NSString *mag) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        
        NSString *regisStr = [objs[@"body"] objectForKey:@"result"];
        int regisInt  = [regisStr intValue];
        
        
        
        if (regisInt == 1) {  // 未注册
            if ([sign isEqualToString:@"Registered"]) {
                success(regisStr);
            }else {
                failure(NSLocalizedString(@"RvcTip_2", nil));
            }
        }else if(regisInt == 2) {  // 注册
            if ([sign isEqualToString:@"Forget"]) {
                success(regisStr);
            }else {
                failure(NSLocalizedString(@"RvcTip_3", nil));
            }
        }else { // 0
            failure(NSLocalizedString(@"RvcTip_4", nil));
        }
        
        
    } returnError:^(NSString *err) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        failure(err);
    }];
}


#pragma mark - 校验手机短信
+ (void)requestWithUrlForVerification:(id)obj andParam:(NSDictionary *)param success:(void(^)(id model))success failure:(void(^)(NSString *err))failure {
    [[UtilToolsClss getUtilTools] addDoLoading];
    
    [NetRequestClss requestWithUrl:@"userInfo/phoneSmsVerify.asp" requestWithParameters:param method:NetMethodPOST returnSuccess:^(id objs, int status, NSString *mag) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        
        int errorNam = [[[objs objectForKey:@"body"] objectForKey:@"error"] intValue];
        NSString *resultStr = [[objs objectForKey:@"body"] objectForKey:@"result"];
        int result   = [resultStr intValue];
        
        if (result == 1) {
            success(resultStr);
        }else {
            NSString *messageStr = [NSString stringWithFormat:@"%ddescription",errorNam];
            failure(NSLocalizedString(messageStr, nil));
        }
        
    } returnError:^(NSString *err) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        failure(err);
    }];
    
    
}


#pragma  mark - 重新设置密码
+ (void)requestWithUrlForForgetPassword:(id)obj andParam:(NSDictionary *)param success:(void(^)(id model))success failure:(void(^)(NSString *err))failure {
    [[UtilToolsClss getUtilTools] addDoLoading];
    [NetRequestClss requestWithUrl:@"userInfo/userReset.asp" requestWithParameters:param method:NetMethodPOST returnSuccess:^(id objs, int status, NSString *mag) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        
        NSString * errorStr  = [[objs objectForKey:@"body"] objectForKey:@"error"];
        NSString * resultStr = [[objs objectForKey:@"body"] objectForKey:@"result"];
        
        if(!errorStr) {
            success(resultStr);
        }else {
            failure(errorStr);
        }
        
    } returnError:^(NSString *err) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        failure(err);
    }];

}

#pragma mark - 账号注册
+(void)requestWithURlForUserRegister:(id)obj andParam:(NSDictionary *)param success:(void (^)(id model))success failure:(void(^)(NSString *err)) failure {
    [[UtilToolsClss getUtilTools] addDoLoading];
    [NetRequestClss requestWithUrl:@"userInfo/userRegister.asp" requestWithParameters:param method:NetMethodGET returnSuccess:^(id objs, int status, NSString *mag) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        
        NSString * resultStr = [[objs objectForKey:@"body"] objectForKey:@"result"];
        NSString * errorStr  = [[objs objectForKey:@"body"] objectForKey:@"error"];
        
        
        if (!errorStr) {
            success(resultStr);
        }else {
            failure(errorStr);
        }


    } returnError:^(NSString *err) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        failure(err);
    }];

}


// 保存 cooke
+ (void)obtainHTTPCookie {
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject:[cookieStorage cookies]];
    [NSUD setValue:cookiesData forKey:@"allCookie"];
    
    
    for (NSHTTPCookie *cookie in [cookieStorage cookies]) {
        if ([cookie.name isEqualToString:JSESSIONID]) {
          NSLog(@"打印cookie：%@",cookie.value);
            [NSUD setObject:cookie.value forKey:MDC_TOKEN];
            break;
        }
    }
}

// 设置头像 － 没用的方法
+ (void)obtainHeadImage:(NSString *)imagerStr {

    if (imagerStr !=  nil || ![imagerStr isEqualToString:@""]) {
        NSURL *url = [NSURL URLWithString:[GET_HEND_IMAGE_IP stringByAppendingString:imagerStr]];
        
        dispatch_queue_t imagaQueue = dispatch_queue_create("headImageQueue", NULL);
        dispatch_async(imagaQueue, ^{
            
            //NSError *imageError;
            NSData *imageData = [NSData dataWithContentsOfURL:url options:0 error:nil];//&imageError];
            
            //if (imageError == nil) {
                NSLog(@"Data:---->%@",imageData);
                if (imageData) {
                    [[NSUserDefaults standardUserDefaults] setObject:imageData forKey:@"headImage"];
                }

           // }
           // if ([NSData dataWithContentsOfURL:url options:0 error:NULL]) {
           //     NSData *imageData = [NSData dataWithContentsOfURL:url options:0 error:NULL];
           //     if (imageData) {
           //         [[NSUserDefaults standardUserDefaults] setObject:imageData forKey:@"headImage"];
           //     }
           // }
        });
    }
}


/** 跳转页面 */
+ (void)loginWithViewController:(UIViewController *)viewController {
       
        [[NSUserDefaults standardUserDefaults]setObject:@"YES" forKey:@"isAutomaticLogin"];
        
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        TabBarC *tab = [storyboard instantiateInitialViewController];
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [UIApplication sharedApplication].statusBarHidden = NO;
        window.rootViewController = tab;
    
//        if (![[GetiPhoneDevice getCurrentDeviceModel] isEqualToString:@"iPhone Simulator"]) {
            [JPUSH sharedJPUSH].sonWindow = window;
            [JPUSH sharedJPUSH].tabBarC    =  tab; //(TabBarC *)self.tabBarController;
            [[JPUSH sharedJPUSH] albbBindChannel]; //这个是绑定推送的账号，问题是如果注册失败会重复执行
//        }
}

/**
 *  清除url缓存
 */





@end
